package com.example.netcenter.MyConverFactory;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import rx.internal.schedulers.NewThreadWorker;

/**
 * CustomResponseConverter
 * hyk
 */
public class CustomResponseConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private TypeAdapter<T> adapter;
    private Type mType;

    private JsonObject ExceptionMap;

    CustomResponseConverter(Gson gson, TypeAdapter<T> mAdapter, Type mType) {
        this.gson = gson;
        this.adapter = mAdapter;
        this.mType = mType;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {


        try {

            String body = value.string();

            JSONObject json = new JSONObject(body);

            JsonReader jsonReader = null;

            InputStream inputStream = new ByteArrayInputStream(body.getBytes());

            jsonReader = gson.newJsonReader(new InputStreamReader(inputStream));

            String code = json.getString("statusCode");

            String data = json.getString("data");

            final String msg = json.getString("statusStr");

            if (code.equals("100000")) {

                if (!data.isEmpty()) {

                    return adapter.read(jsonReader);
                }
                return (T) "请求成功";

            } else {

                ExceptionMap = new JsonObject();
                ExceptionMap.addProperty("Code", code);
                ExceptionMap.addProperty("Msg", msg);
                throw new Exception(ExceptionMap.toString());


            }
        } catch (Exception e) {
            Log.e("Conker", "convert: " + e.getLocalizedMessage());
            throw new RuntimeException(e.getMessage());

        } finally {
            value.close();
        }

    }
}
